// 整个P2P控制端逻辑放在这边写
const { ipcRenderer } = require("electron");
const EventEmmitter = require("events");
// 有事件的时候先通过 peer Emitter 一个事件，然后app.js 再去处理
const peer = new EventEmmitter();

// async function getScreenStream() {
//   // 捕获桌面流的过程
//   const sources = await ipcRenderer.invoke("desktopCapturer-getSources");
//   navigator.webkitGetUserMedia(
//     {
//       audio: false,
//       video: {
//         mandatory: {
//           chromeMediaSource: "desktop",
//           chromeMediaSourceId: sources[0].id,
//           widht: window.screen.width,
//           height: window.screen.height,
//         },
//       },
//     },
//     (stream) => {
//       peer.emit("add-stream", stream);
//       // ipcRenderer.send("add-stream", stream);
//     },
//     (err) => {
//       console.log(err);
//     }
//   );
// }
// getScreenStream();

// 监听 peer 的 robot 事件
peer.on("robot", (type, data) => {
  // 特殊处理，傀儡端在响应的时候，如果是鼠标事件，需要添加screen
  if (type === "mouse") {
    data.screen = {
      width: window.screen.width,
      height: window.screen.height,
    };
  }
  // 除非 ipc 与主进程 的 robot通信
  ipcRenderer.send("robot", type, data);
});

// 控制端
// 控制端创建 peer 对象
const pc = new RTCPeerConnection({});
/** STUN打洞 */
pc.onicecandidate = (e) => {
  if (e.candidate) {
    // 这个事件在 RTCPeerConnection 创建成功自动发起
    // 发送 candidate 到傀儡端
    console.log(
      "🚀 ~ peer-control.js:40 ~ pc.onicecandidate ~ e.candidate:",
      JSON.stringify(e.candidate)
    );
    ipcRenderer.send("forward", "control-candidate", e.candidate);
  }
};
// 接收后面傀儡端发送过来的 IceEvent(一样的事情傀儡度端再做一遍)
let candidates = [];
async function addIceCandidate(candidate) {
  // pc.remoteDescription 没设置完成，先将candidate 放缓冲池存起来
  // 有可能是 null
  if (candidate) {
    candidates.push(candidate);
  }
  // 等待 pc.remoteDescription 设置完成后再添加 IceCandidate
  if (pc.remoteDescription && pc.remoteDescription.type) {
    for (let i = 0; i < candidates.length; i++) {
      await pc.addIceCandidate(new RTCIceCandidate(candidates[i]));
    }
    candidates = [];
  }
}
ipcRenderer.on("candidate", (e, candidate) => {
  addIceCandidate(candidate);
});
// window.addIceCandidate = addIceCandidate;
/** STUN打洞 ======= end ====== */

// 控制端通过 pc 创建 offer
async function createOffer() {
  const offer = await pc.createOffer({
    offerToReceiveAudio: false,
    offerToReceiveVideo: true,
  });
  await pc.setLocalDescription(offer);
  console.log(
    "🚀 ~ peer-control.js:61 ~ createOffer ~ offer:",
    JSON.stringify(offer)
  );
  return pc.localDescription;
}

peer.on("get-offer", async (e) => {
  let offer = await createOffer();
  // 发送 offer 到傀儡端
  ipcRenderer.send("forward", "offer", { type: offer.type, sdp: offer.sdp });
});

// 傀儡端确认，控制端得到傀儡端的 answer SDP 后的操作
async function setRemote(answer) {
  console.log("🚀 ~ peer-control.js:106 ~ setRemote ~ answer:", answer);
  const answerJson = JSON.stringify(answer);
  console.log("🚀 ~ peer-control.js:110 ~ setRemote ~ answerJson:", answerJson);
  await pc.setRemoteDescription(answerJson);
}
// ipcRenderer.on("answer", async (e, answer) => {
//   console.log("🚀 ~ peer-control.js:109 ~ ipcRenderer.on ~ answer:", answer);
//   console.log("🚀 ~ peer-control.js:110 ~ ipcRenderer.on ~ answer:", e);

//   // 收到 answer 事件
//   await setRemote(answer);
// });
window.setRemote = setRemote;
exports.setRemote = setRemote; // 为了演示暴露出去调用
// 控制端监听傀儡端发来的 stream 增加
pc.ontrack = (e) => {
  if (e.streams && e.streams[0]) {
    peer.emit("add-stream", e.streams[0]);
  }
};
// pc.onaddstream((stream) => {
//   peer.emit("add-stream", stream);
// });
exports.peer = peer;
